// 通知服务 - 管理浏览器通知和Service Worker
export interface NotificationSettings {
  enabled: boolean;
  taskReminders: boolean;
  dailySummary: boolean;
  weeklyReview: boolean;
  overdueAlerts: boolean;
  reminderTime: string; // HH:MM格式
  soundEnabled: boolean;
  vibrationEnabled: boolean;
}

export interface TaskNotification {
  id: string;
  taskId: string;
  title: string;
  message: string;
  type: 'reminder' | 'overdue' | 'summary' | 'deadline';
  scheduledTime: Date;
  sent: boolean;
}

class NotificationService {
  private static instance: NotificationService;
  private serviceWorker: ServiceWorkerRegistration | null = null;
  private settings: NotificationSettings;

  private constructor() {
    this.settings = this.loadSettings();
    this.initServiceWorker();
  }

  public static getInstance(): NotificationService {
    if (!NotificationService.instance) {
      NotificationService.instance = new NotificationService();
    }
    return NotificationService.instance;
  }

  // 初始化Service Worker
  private async initServiceWorker(): Promise<void> {
    if ('serviceWorker' in navigator) {
      try {
        const registration = await navigator.serviceWorker.register('/sw.js');
        this.serviceWorker = registration;
        console.log('Service Worker 注册成功:', registration);

        // 监听Service Worker更新
        registration.addEventListener('updatefound', () => {
          console.log('Service Worker 更新可用');
        });

        // 监听消息
        navigator.serviceWorker.addEventListener('message', (event) => {
          console.log('收到Service Worker消息:', event.data);
        });

      } catch (error) {
        console.error('Service Worker 注册失败:', error);
      }
    }
  }

  // 请求通知权限
  public async requestPermission(): Promise<NotificationPermission> {
    if (!('Notification' in window)) {
      console.warn('此浏览器不支持通知');
      return 'denied';
    }

    if (Notification.permission === 'granted') {
      return 'granted';
    }

    if (Notification.permission !== 'denied') {
      const permission = await Notification.requestPermission();
      return permission;
    }

    return Notification.permission;
  }

  // 检查通知权限状态
  public getPermissionStatus(): NotificationPermission {
    if (!('Notification' in window)) {
      return 'denied';
    }
    return Notification.permission;
  }

  // 显示即时通知
  public async showNotification(title: string, options: {
    body?: string;
    icon?: string;
    badge?: string;
    tag?: string;
    data?: any;
    actions?: any[];
    requireInteraction?: boolean;
  } = {}): Promise<void> {
    const permission = await this.requestPermission();
    if (permission !== 'granted') {
      console.warn('通知权限被拒绝');
      return;
    }

    const defaultOptions = {
      body: options.body || '',
      icon: options.icon || '/icon-192x192.png',
      badge: options.badge || '/icon-192x192.png',
      tag: options.tag || `notification-${Date.now()}`,
      data: options.data || {},
      vibrate: this.settings.vibrationEnabled ? [200, 100, 200] : [],
      silent: !this.settings.soundEnabled,
      requireInteraction: options.requireInteraction || false,
      actions: options.actions || []
    };

    if (this.serviceWorker) {
      // 使用Service Worker显示通知
      await this.serviceWorker.showNotification(title, defaultOptions);
    } else {
      // 使用浏览器原生通知
      new Notification(title, defaultOptions);
    }
  }

  // 安排任务提醒
  public async scheduleTaskReminder(taskId: string, title: string, dueDate: Date, reminderMinutes: number = 30): Promise<void> {
    if (!this.settings.enabled || !this.settings.taskReminders) {
      return;
    }

    const reminderTime = new Date(dueDate.getTime() - (reminderMinutes * 60 * 1000));
    const now = new Date();

    if (reminderTime <= now) {
      // 如果提醒时间已过，立即显示
      await this.showNotification('任务提醒', {
        body: `任务"${title}"即将到期`,
        tag: `task-reminder-${taskId}`,
        data: { taskId, type: 'reminder' },
        requireInteraction: true
      });
      return;
    }

    // 计算延迟时间
    const delay = reminderTime.getTime() - now.getTime();

    // 使用setTimeout安排提醒（注意：页面关闭后会失效）
    setTimeout(async () => {
      await this.showNotification('任务提醒', {
        body: `任务"${title}"将在${reminderMinutes}分钟后到期`,
        tag: `task-reminder-${taskId}`,
        data: { taskId, type: 'reminder' },
        requireInteraction: true,
        actions: [
          { action: 'view', title: '查看任务', icon: '/icon-192x192.png' },
          { action: 'snooze', title: '稍后提醒', icon: '/icon-192x192.png' }
        ]
      });
    }, delay);

    console.log(`已安排任务提醒: ${title}, 提醒时间: ${reminderTime.toLocaleString()}`);
  }

  // 显示逾期任务通知
  public async showOverdueNotification(tasks: Array<{ id: string; title: string; dueDate: Date }>): Promise<void> {
    if (!this.settings.enabled || !this.settings.overdueAlerts) {
      return;
    }

    const count = tasks.length;
    const title = count === 1 ? '任务逾期提醒' : `${count}个任务逾期提醒`;
    const body = count === 1 
      ? `任务"${tasks[0].title}"已逾期` 
      : `您有${count}个任务已逾期，请及时处理`;

    await this.showNotification(title, {
      body,
      tag: 'overdue-tasks',
      data: { type: 'overdue', taskIds: tasks.map(t => t.id) },
      requireInteraction: true,
      actions: [
        { action: 'view-overdue', title: '查看逾期任务', icon: '/icon-192x192.png' },
        { action: 'dismiss', title: '忽略', icon: '/icon-192x192.png' }
      ]
    });
  }

  // 显示每日总结通知
  public async showDailySummary(summary: {
    completed: number;
    pending: number;
    overdue: number;
    upcomingDeadlines: number;
  }): Promise<void> {
    if (!this.settings.enabled || !this.settings.dailySummary) {
      return;
    }

    const body = `今日完成${summary.completed}个任务，还有${summary.pending}个待办，${summary.overdue}个逾期`;

    await this.showNotification('每日工作总结', {
      body,
      tag: 'daily-summary',
      data: { type: 'daily-summary', summary },
      actions: [
        { action: 'view-stats', title: '查看统计', icon: '/icon-192x192.png' }
      ]
    });
  }

  // 加载设置
  private loadSettings(): NotificationSettings {
    const saved = localStorage.getItem('aide_notification_settings');
    const defaultSettings: NotificationSettings = {
      enabled: true,
      taskReminders: true,
      dailySummary: true,
      weeklyReview: true,
      overdueAlerts: true,
      reminderTime: '09:00',
      soundEnabled: true,
      vibrationEnabled: true
    };

    if (saved) {
      try {
        return { ...defaultSettings, ...JSON.parse(saved) };
      } catch (error) {
        console.error('解析通知设置失败:', error);
        return defaultSettings;
      }
    }

    return defaultSettings;
  }

  // 保存设置
  public saveSettings(settings: Partial<NotificationSettings>): void {
    this.settings = { ...this.settings, ...settings };
    localStorage.setItem('aide_notification_settings', JSON.stringify(this.settings));
    console.log('通知设置已保存:', this.settings);
  }

  // 获取当前设置
  public getSettings(): NotificationSettings {
    return { ...this.settings };
  }

  // 清除所有通知
  public async clearAllNotifications(): Promise<void> {
    if (this.serviceWorker) {
      const notifications = await this.serviceWorker.getNotifications();
      notifications.forEach(notification => notification.close());
    }
  }

  // 清除特定标签的通知
  public async clearNotificationsByTag(tag: string): Promise<void> {
    if (this.serviceWorker) {
      const notifications = await this.serviceWorker.getNotifications({ tag });
      notifications.forEach(notification => notification.close());
    }
  }

  // 测试通知
  public async testNotification(): Promise<void> {
    await this.showNotification('测试通知', {
      body: '这是一个测试通知，用于验证通知功能是否正常工作',
      tag: 'test-notification',
      requireInteraction: false
    });
  }
}

export default NotificationService;
